package Code.Test7;

public class StudentTest {
    public static void main(String[] args) {

        //创建学生数组
        Student[] arr = new Student[3];

        //储存个学生对象
        Student s1 = new Student("hiema002", "zhangsan", 18);
        Student s2 = new Student("002", "lisi", 19);
        Student s3 = new Student("003", "wangwu", 20);
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = s3;

        //添加一个学生后遍历
        System.out.println("添加");
        arr = Addition(arr,"004","wangheng",24);
        Traversal(arr);

        //删除一个学生后遍历
        System.out.println("删除");
        arr = Delete(arr,"004");
        Traversal(arr);

        //查询
        System.out.println("查询");
        if (find(arr,"hiema002")){
            for (int i = 0; i < arr.length; i++) {
                if (arr[i].getId() == "hiema002"){
                    arr[i].setAge(arr[i].getAge()+1);
                }
            }
        }
        Traversal(arr);


    }

    //遍历所有学生信息
    public static void Traversal(Student[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i].show();
        }
    }

    //查找
    public static boolean find(Student[] arr, String id) {
        for (int i = 0; i < arr.length; i++) {
            if (id == arr[i].getId()) {
                return true;
            }
        }
        return false;
    }

    //添加
    public static Student[] Addition(Student[] arr, String id, String name, int age) {
        //创建新增人员的数组
        Student[] newArr = new Student[arr.length + 1];

        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }

        //创建新添加的对象
        Student s = new Student(id, name, age);

        if (!find(arr,id)){
            newArr[newArr.length-1] = s;
            return newArr;
        }else {
            System.out.println("添加失败");
            return arr;
        }
    }

    //删除
    public static Student[] Delete(Student[] arr,String id){
        Student[] newArr = new Student[arr.length - 1];

        if (find(arr, id)) {
            int index = 0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i].getId() == id){
                    continue;
                }else {
                    newArr[index] = arr[i];
                    index++;
                }
            }
            return newArr;
        }else {
            System.out.println("删除失败");
            return arr;
        }

    }

}
